package com.southminority.ethnic.service.research.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.southminority.ethnic.common.exception.BusinessException;
import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.mapper.research.IntellectualPropertyMapper;
import com.southminority.ethnic.pojo.IntellectualProperty;
import com.southminority.ethnic.service.research.IntellectualPropertyService;
import com.southminority.ethnic.controller.research.vo.IntellectualPropertyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 知识产权服务实现类
 * 
 * @author SouthMinority
 */
@Slf4j
@Service
@Transactional
public class IntellectualPropertyServiceImpl implements IntellectualPropertyService {

    private final IntellectualPropertyMapper intellectualPropertyMapper;
    private final ObjectMapper objectMapper;

    public IntellectualPropertyServiceImpl(IntellectualPropertyMapper intellectualPropertyMapper,
                                         ObjectMapper objectMapper) {
        this.intellectualPropertyMapper = intellectualPropertyMapper;
        this.objectMapper = objectMapper;
    }

    // ==================== 前端展示接口实现 ====================

    @Override
    public List<IntellectualPropertyVO> getIntellectualPropertyList() {
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByDesc("sort_order")
               .orderByDesc("authorization_date")
               .orderByDesc("application_date");
        
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectList(wrapper);
        return intellectualPropertyList.stream()
                                     .map(this::convertToVO)
                                     .collect(Collectors.toList());
    }

    @Override
    public List<IntellectualPropertyVO> getFeaturedIntellectualPropertyList() {
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("is_featured", 1)
               .orderByAsc("sort_order")
               .orderByDesc("authorization_date");
        
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectList(wrapper);
        return intellectualPropertyList.stream()
                                     .map(this::convertToVO)
                                     .collect(Collectors.toList());
    }

    @Override
    public IntellectualPropertyVO getIntellectualPropertyDetail(Long id) {
        IntellectualProperty intellectualProperty = intellectualPropertyMapper.selectById(id);
        if (intellectualProperty == null || intellectualProperty.getStatus() == -1) {
            throw new BusinessException("知识产权不存在");
        }
        
        return convertToVO(intellectualProperty);
    }

    @Override
    public List<IntellectualPropertyVO> getIntellectualPropertyListByType(String type) {
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("type", type)
               .orderByDesc("authorization_date")
               .orderByDesc("application_date");
        
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectList(wrapper);
        return intellectualPropertyList.stream()
                                     .map(this::convertToVO)
                                     .collect(Collectors.toList());
    }

    @Override
    public List<IntellectualPropertyVO> getIntellectualPropertyListByYear(Integer year) {
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .and(qw -> qw.apply("YEAR(authorization_date) = {0}", year)
                           .or()
                           .apply("YEAR(application_date) = {0}", year))
               .orderByDesc("authorization_date")
               .orderByDesc("application_date");
        
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectList(wrapper);
        return intellectualPropertyList.stream()
                                     .map(this::convertToVO)
                                     .collect(Collectors.toList());
    }

    @Override
    public List<IntellectualPropertyVO> getIntellectualPropertyListByLegalStatus(String legalStatus) {
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("legal_status", legalStatus)
               .orderByDesc("authorization_date")
               .orderByDesc("application_date");
        
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectList(wrapper);
        return intellectualPropertyList.stream()
                                     .map(this::convertToVO)
                                     .collect(Collectors.toList());
    }

    // ==================== 管理端接口实现 ====================

    @Override
    public PageResult<IntellectualPropertyVO> getIntellectualPropertyPage(Integer page, Integer size, 
                                                                        String keyword, String type, 
                                                                        String legalStatus, Integer status) {
        // 创建分页对象
        Page<IntellectualProperty> pageObj = new Page<>(page, size);
        
        // 构建查询条件
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        
        // 搜索关键词（标题、发明人、申请人）
        if (StringUtils.hasText(keyword)) {
            wrapper.and(qw -> qw.like("title", keyword)
                              .or().like("inventors", keyword)
                              .or().like("applicant", keyword)
                              .or().like("keywords", keyword));
        }
        
        // 类型筛选
        if (StringUtils.hasText(type)) {
            wrapper.eq("type", type);
        }
        
        // 法律状态筛选
        if (StringUtils.hasText(legalStatus)) {
            wrapper.eq("legal_status", legalStatus);
        }
        
        // 状态筛选
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.ne("status", -1); // 默认不显示已删除的
        }
        
        // 排序
        wrapper.orderByDesc("is_featured")
               .orderByAsc("sort_order")
               .orderByDesc("authorization_date")
               .orderByDesc("application_date");
        
        // 执行分页查询
        IPage<IntellectualProperty> pageResult = intellectualPropertyMapper.selectPage(pageObj, wrapper);
        
        // 转换为VO并构建分页结果
        List<IntellectualPropertyVO> voList = pageResult.getRecords().stream()
                                                      .map(this::convertToVO)
                                                      .collect(Collectors.toList());
        
        return PageResult.<IntellectualPropertyVO>builder()
                .current(pageResult.getCurrent())
                .size(pageResult.getSize())
                .total(pageResult.getTotal())
                .pages(pageResult.getPages())
                .records(voList)
                .build();
    }

    @Override
    public List<IntellectualPropertyVO> getAllIntellectualPropertyList() {
        QueryWrapper<IntellectualProperty> wrapper = new QueryWrapper<>();
        wrapper.ne("status", -1)
               .orderByDesc("is_featured")
               .orderByAsc("sort_order")
               .orderByDesc("authorization_date");
        
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectList(wrapper);
        return intellectualPropertyList.stream()
                                     .map(this::convertToVO)
                                     .collect(Collectors.toList());
    }

    @Override
    public boolean createIntellectualProperty(IntellectualPropertyVO intellectualPropertyVO) {
        IntellectualProperty intellectualProperty = convertFromVO(intellectualPropertyVO);
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        intellectualProperty.setCreateTime(now);
        intellectualProperty.setUpdateTime(now);
        
        // 设置默认值
        if (intellectualProperty.getStatus() == null) {
            intellectualProperty.setStatus(1);
        }
        if (intellectualProperty.getIsFeatured() == null) {
            intellectualProperty.setIsFeatured(0);
        }
        if (intellectualProperty.getSortOrder() == null) {
            intellectualProperty.setSortOrder(0);
        }
        
        return intellectualPropertyMapper.insert(intellectualProperty) > 0;
    }

    @Override
    public boolean updateIntellectualProperty(IntellectualPropertyVO intellectualPropertyVO) {
        if (intellectualPropertyVO.getId() == null) {
            throw new BusinessException("知识产权ID不能为空");
        }
        
        IntellectualProperty existingIntellectualProperty = intellectualPropertyMapper.selectById(intellectualPropertyVO.getId());
        if (existingIntellectualProperty == null) {
            throw new BusinessException("知识产权不存在");
        }

        // 转换前端VO -> 实体，并仅更新非空字段，避免把未编辑字段覆盖为null
        IntellectualProperty payload = convertFromVO(intellectualPropertyVO);

        // 记录更新前的实体
        log.info("[IP][Update] id={}, beforeDB={}", intellectualPropertyVO.getId(), existingIntellectualProperty);
        log.info("[IP][Update] payload={}", payload);

        UpdateWrapper<IntellectualProperty> uw = new UpdateWrapper<>();
        uw.eq("id", intellectualPropertyVO.getId());

        // 字段逐一判空设置
        if (payload.getTitle() != null) uw.set("title", payload.getTitle());
        if (payload.getType() != null) uw.set("type", payload.getType());
        if (payload.getApplicationNumber() != null) uw.set("application_number", payload.getApplicationNumber());
        if (payload.getAuthorizationNumber() != null) uw.set("authorization_number", payload.getAuthorizationNumber());
        if (payload.getApplicationDate() != null) uw.set("application_date", payload.getApplicationDate());
        if (payload.getAuthorizationDate() != null) uw.set("authorization_date", payload.getAuthorizationDate());
        if (payload.getPublicationDate() != null) uw.set("publication_date", payload.getPublicationDate());
        if (payload.getInventors() != null) uw.set("inventors", payload.getInventors());
        if (payload.getApplicant() != null) uw.set("applicant", payload.getApplicant());
        if (payload.getAgent() != null) uw.set("agent", payload.getAgent());
        if (payload.getDescription() != null) uw.set("description", payload.getDescription());
        if (payload.getTechnicalField() != null) uw.set("technical_field", payload.getTechnicalField());
        if (payload.getMainClaims() != null) uw.set("main_claims", payload.getMainClaims());
        if (payload.getClassificationNumber() != null) uw.set("classification_number", payload.getClassificationNumber());
        if (payload.getLegalStatus() != null) uw.set("legal_status", payload.getLegalStatus());
        if (payload.getCertificateUrl() != null) uw.set("certificate_url", payload.getCertificateUrl());
        if (payload.getAttachmentUrls() != null) uw.set("attachment_urls", payload.getAttachmentUrls());
        if (payload.getKeywords() != null) uw.set("keywords", payload.getKeywords());
        if (payload.getEconomicValue() != null) uw.set("economic_value", payload.getEconomicValue());
        if (payload.getCooperationInfo() != null) uw.set("cooperation_info", payload.getCooperationInfo());
        if (payload.getSortOrder() != null) uw.set("sort_order", payload.getSortOrder());
        if (payload.getIsFeatured() != null) uw.set("is_featured", payload.getIsFeatured());
        if (payload.getStatus() != null) uw.set("status", payload.getStatus());

        uw.set("update_time", LocalDateTime.now());

        int affected = intellectualPropertyMapper.update(null, uw);
        log.info("[IP][Update] affectedRows={}", affected);

        IntellectualProperty after = intellectualPropertyMapper.selectById(intellectualPropertyVO.getId());
        log.info("[IP][Update] afterDB={}", after);

        return affected > 0;
    }

    @Override
    public boolean deleteIntellectualProperty(Long id) {
        IntellectualProperty intellectualProperty = intellectualPropertyMapper.selectById(id);
        if (intellectualProperty == null) {
            throw new BusinessException("知识产权不存在");
        }
        
        // 软删除：设置状态为-1
        intellectualProperty.setStatus(-1);
        intellectualProperty.setUpdateTime(LocalDateTime.now());
        
        return intellectualPropertyMapper.updateById(intellectualProperty) > 0;
    }

    @Override
    public boolean batchDeleteIntellectualProperty(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("删除的知识产权ID列表不能为空");
        }
        
        // 批量软删除
        List<IntellectualProperty> intellectualPropertyList = intellectualPropertyMapper.selectBatchIds(ids);
        if (intellectualPropertyList.isEmpty()) {
            throw new BusinessException("未找到要删除的知识产权");
        }
        
        LocalDateTime now = LocalDateTime.now();
        intellectualPropertyList.forEach(intellectualProperty -> {
            intellectualProperty.setStatus(-1);
            intellectualProperty.setUpdateTime(now);
        });
        
        // 批量更新
        int updatedCount = 0;
        for (IntellectualProperty intellectualProperty : intellectualPropertyList) {
            updatedCount += intellectualPropertyMapper.updateById(intellectualProperty);
        }
        
        return updatedCount == intellectualPropertyList.size();
    }

    @Override
    public boolean updateIntellectualPropertyStatus(Long id, Integer status) {
        IntellectualProperty intellectualProperty = intellectualPropertyMapper.selectById(id);
        if (intellectualProperty == null) {
            throw new BusinessException("知识产权不存在");
        }
        
        intellectualProperty.setStatus(status);
        intellectualProperty.setUpdateTime(LocalDateTime.now());
        
        return intellectualPropertyMapper.updateById(intellectualProperty) > 0;
    }

    @Override
    public boolean setIntellectualPropertyFeatured(Long id, Integer isFeatured) {
        IntellectualProperty intellectualProperty = intellectualPropertyMapper.selectById(id);
        if (intellectualProperty == null) {
            throw new BusinessException("知识产权不存在");
        }
        
        intellectualProperty.setIsFeatured(isFeatured);
        intellectualProperty.setUpdateTime(LocalDateTime.now());
        
        return intellectualPropertyMapper.updateById(intellectualProperty) > 0;
    }

    // ==================== 私有方法 ====================

    /**
     * 将IntellectualProperty转换为IntellectualPropertyVO
     */
    private IntellectualPropertyVO convertToVO(IntellectualProperty intellectualProperty) {
        IntellectualPropertyVO vo = new IntellectualPropertyVO();
        BeanUtils.copyProperties(intellectualProperty, vo);
        
        // 处理JSON字段
        try {
            // 发明人列表
            if (StringUtils.hasText(intellectualProperty.getInventors())) {
                List<String> inventors = Arrays.asList(intellectualProperty.getInventors().split(","));
                vo.setInventors(inventors.stream().map(String::trim).collect(Collectors.toList()));
            } else {
                vo.setInventors(new ArrayList<>());
            }
            
            // 附件URLs
            if (StringUtils.hasText(intellectualProperty.getAttachmentUrls())) {
                List<Map<String, String>> attachmentUrls = objectMapper.readValue(
                    intellectualProperty.getAttachmentUrls(), 
                    new TypeReference<List<Map<String, String>>>() {}
                );
                vo.setAttachmentUrls(attachmentUrls);
            } else {
                vo.setAttachmentUrls(new ArrayList<>());
            }
            
            // 关键词列表
            if (StringUtils.hasText(intellectualProperty.getKeywords())) {
                List<String> keywords = Arrays.asList(intellectualProperty.getKeywords().split(","));
                vo.setKeywords(keywords.stream().map(String::trim).collect(Collectors.toList()));
            } else {
                vo.setKeywords(new ArrayList<>());
            }
        } catch (Exception e) {
            log.error("转换JSON字段失败", e);
            vo.setInventors(new ArrayList<>());
            vo.setAttachmentUrls(new ArrayList<>());
            vo.setKeywords(new ArrayList<>());
        }
        
        // 设置显示名称
        vo.setTypeDisplay(getTypeDisplay(intellectualProperty.getType()));
        vo.setLegalStatusDisplay(getLegalStatusDisplay(intellectualProperty.getLegalStatus()));
        vo.setStatusDisplay(getStatusDisplay(intellectualProperty.getStatus()));
        
        // 设置年份
        if (intellectualProperty.getApplicationDate() != null) {
            vo.setApplicationYear(intellectualProperty.getApplicationDate().getYear());
        }
        if (intellectualProperty.getAuthorizationDate() != null) {
            vo.setAuthorizationYear(intellectualProperty.getAuthorizationDate().getYear());
        }
        
        return vo;
    }

    /**
     * 将IntellectualPropertyVO转换为IntellectualProperty
     */
    private IntellectualProperty convertFromVO(IntellectualPropertyVO vo) {
        IntellectualProperty intellectualProperty = new IntellectualProperty();
        BeanUtils.copyProperties(vo, intellectualProperty);
        
        // 处理JSON字段
        try {
            // 发明人列表
            if (vo.getInventors() != null && !vo.getInventors().isEmpty()) {
                String inventors = String.join(",", vo.getInventors());
                intellectualProperty.setInventors(inventors);
            } else {
                intellectualProperty.setInventors(null);
            }
            
            // 附件URLs - 确保空数组也会被正确处理
            if (vo.getAttachmentUrls() != null) {
                if (!vo.getAttachmentUrls().isEmpty()) {
                    String attachmentUrls = objectMapper.writeValueAsString(vo.getAttachmentUrls());
                    intellectualProperty.setAttachmentUrls(attachmentUrls);
                } else {
                    // 空数组设置为空字符串或null，清除旧值
                    intellectualProperty.setAttachmentUrls(null);
                }
            }
            
            // 关键词列表
            if (vo.getKeywords() != null && !vo.getKeywords().isEmpty()) {
                String keywords = String.join(",", vo.getKeywords());
                intellectualProperty.setKeywords(keywords);
            } else {
                intellectualProperty.setKeywords(null);
            }
        } catch (Exception e) {
            log.error("转换JSON字段失败", e);
        }
        
        return intellectualProperty;
    }

    /**
     * 获取类型显示名称
     */
    private String getTypeDisplay(String type) {
        if (type == null) return "";
        switch (type) {
            case "patent":
                return "发明专利";
            case "utility":
                return "实用新型";
            case "software":
                return "软件著作权";
            case "dataset":
                return "数据集";
            case "trademark":
                return "商标";
            default:
                return type;
        }
    }

    /**
     * 获取法律状态显示名称
     */
    private String getLegalStatusDisplay(String legalStatus) {
        if (legalStatus == null) return "";
        switch (legalStatus) {
            case "pending":
                return "待审";
            case "granted":
                return "已授权";
            case "rejected":
                return "被驳回";
            case "expired":
                return "已过期";
            default:
                return legalStatus;
        }
    }

    /**
     * 获取状态显示名称
     */
    private String getStatusDisplay(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 1:
                return "启用";
            case 0:
                return "禁用";
            case -1:
                return "已删除";
            default:
                return String.valueOf(status);
        }
    }
} 
